<?php

class fop_Object_Fopline {

  protected $_name;
  protected $_tableName;
  protected $_description;
  protected $_creatorEmail;
  protected $_creationDate;
  
  /* definition of the nonce table */
  static protected $_dbFoplineTableName = 'foplines';
  static protected $_dbFoplineNameCol = 'name';
  static protected $_dbFoplineTableNameCol = 'tableName';
  static protected $_dbFoplineDescriptionCol = 'description';
  static protected $_dbFoplineCreatorEmailCol = 'creatorEmail';
  static protected $_dbFoplineCreationdateCol = 'creationDate';  


  static protected $_allowedRenderMode = array('FOPTable','RegularExpression');  

  public function __construct($name,$tableName,$data = array()) {
  	
  	if(empty($data)) {
   	  //We validate the name
  	  self::_validateName($name);
  	  self::_validateName($tableName);
  	  $name = strToUpper($name);
  	  $tableName = strToUpper($tableName);
  	  //We get the data from the database
      $db = Zend_Registry::get('dt_dbs')->getDb('fop','fopline','key');
      $select = $db->select()->from(self::$_dbFoplineTableName);
      $select->where($db->quoteInto(self::$_dbFoplineNameCol ." = ?", $name));
      $select->where($db->quoteInto(self::$_dbFoplineTableNameCol ." = ?", $tableName));
      $res = $db->fetchAll($select->__toString());

          
      if(empty($res)) {
  	    require_once('fop/objects/Exception.php');
  	    throw new fop_Object_Exception('Fopline not found',8); 
      }

    $data = $res[0];
  	}
    $this->_name = $data[self::$_dbFoplineNameCol];
    $this->_tableName = $data[self::$_dbFoplineTableNameCol];
    $this->_description = $data[self::$_dbFoplineDescriptionCol];
    $this->_creatorEmail = $data[self::$_dbFoplineCreatorEmailCol];
    $this->_creationDate = $data[self::$_dbFoplineCreationdateCol];	

      	
  }	//end constructor


  public function getName() {
    return $this->_name;	
  }
  public function asArray() {
  	$results = array();
    $results['name'] = $this->_name;
    $results['tableName'] = $this->_tableName;
    $results['description'] = $this->_description;
    $results['creatorEmail'] = $this->_creatorEmail;
    $results['creationDate'] = $this->_creationDate;	  	
    return $results;
  }
  
  
  public function getHistory() {
  	require_once('fop/objects/message.php');
  	$message = new fop_Object_Message($this->_name,$this->_tableName,'','','' ,array(),'whatever');
  	return $message->getHistory();	
  }
	
  static public function listing($tableName) {
    $db = Zend_Registry::get('dt_dbs')->getDb('fop','fopline','key');
    $select = $db->select()->from(self::$_dbFoplineTableName);
    $select->where($db->quoteInto(self::$_dbFoplineTableNameCol ." = ?", $tableName));
    $res = $db->fetchAll($select->__toString());  

    if(empty($res)) return array();

    //We must reinterpret the rows so it is independant to the way it is stored
    $results = array();
    foreach($res as $num => $row) {
    	$fopline = new fop_Object_Fopline('','',$row);
    	$results[] = $fopline->asArray();	
    }
    
    return $results;
      
  } //end list
  
  
  
  //This function returns an array with the matching or not and if yes, the data that matches
  public function matchCryptic($crypticEntry) {
      $regExp = $this->render('RegularExpression');
      $crypticEntry = strToUpper(preg_replace('/ /','',$crypticEntry));
      $Ok = preg_match($regExp,$crypticEntry,$matches);
      if($Ok) {
		
		if(!empty($matches)) {
			$matchingData = array();
			foreach($matches as $name => $value) {
				if(preg_match('/^match/',$name)) {
					if(!empty($value)) $matchingData[substr($name, 5)] = $value;	
				}	
			} //end foreach	
		} //end matches
		return array('ok' => $Ok,'matchingData' => $matchingData);
	} else return array('ok' => $Ok);
	
	 
	
      
  }
  
  static public function create($params) {
  	
  	//We clean the data provided
  	//We validate the name
  	self::_validateName($params['name']);
  	$name = strToUpper($params['name']);

  	  	
    require_once('fop/objects/table.php');

	Zend_Registry::get('dt_log')->log('searching fop table to create fop. table:'.$params['tableName'], Zend_Log::DEBUG);

    $table = new fop_Object_Table($params['tableName']);
  	$tableName = $table->getName();
  	
  	//We clean the description, only constraint is that it should be valid HTML
	require_once('htmlpurifier/library/HTMLPurifier.auto.php');
  	$purifier = new HTMLPurifier();
    $description = $purifier->purify($params['description']);

    //We check if the Fopline is not already existing
    $existing = true;
    try{
    	$fopline = new fop_Object_Fopline($name,$tableName);
    } catch(fop_Object_Exception $e) {
    	$existing = false;	
    }
    if($existing) {
  	    require_once('fop/objects/Exception.php');
  	    throw new fop_Object_Exception('Fopline is already existing',10);     	
    }


    //OK we can create the Fopline
	$email = Zend_Registry::get('app_user')->getEmail();
  	$creationDate = time();
  	
  	$data = array(
      self::$_dbFoplineNameCol => $name,
      self::$_dbFoplineTableNameCol => $tableName,
      self::$_dbFoplineDescriptionCol => $description,
      self::$_dbFoplineCreatorEmailCol => $email,
      self::$_dbFoplineCreationdateCol => $creationDate  	
  	);
    $db = Zend_Registry::get('dt_dbs')->getDb('fop','fopline','key');
    $db->insert(self::$_dbFoplineTableName, $data); 	
  	
  	//ok we now create the first message for the fopline
  	require_once('fop/objects/message.php');  	
  	fop_Object_Message::createBase(array('foplineName'=>$name,'tableName'=>$tableName));
  	return true;
  	
  } //end create

  static protected function	_validateName($name) {
    
    if(empty($name)) {
  	  require_once('fop/objects/Exception.php');
  	  throw new fop_Object_Exception('Mandatory data is missing',0);
    }
    
    //Fopline and table name can only be lowercase alphabet characters and less or equal 32 characters
  	if(preg_match('/[^a-zA-Z0-9]/',$name)) {
  	  require_once('fop/objects/Exception.php');
  	  throw new fop_Object_Exception('Fopline or table name can only be alphabet lower case characters or numeric',2);  		
  	}
  	if(32 < strlen($name)) {
  	  require_once('fop/objects/Exception.php');
  	  throw new fop_Object_Exception('Fopline or table name must be less than 33 characters',3);
  	}
  	return true;	
  }
  
  public function render($mode) {
	if(!in_array($mode,self::$_allowedRenderMode)) {
  	  require_once('fop/objects/Exception.php');
  	  throw new fop_Object_Exception('Mode is not an authorized render mode',3);		
	}
	
	//We load the current version of the message
    require_once('fop/objects/message.php');
    $message = new fop_Object_Message($this->_name,$this->_tableName,'','current');
    //We render it
	return $message->render($mode);

    
    
    
  }//end render
  
}